package com.ddl.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ddl.common.enums.ErrorCode;
import com.ddl.common.enums.Platform;
import com.ddl.common.exception.BusinessException;
import com.ddl.common.exception.ExceptionUtil;
import com.ddl.common.exception.ResultModel;
import com.ddl.dao.UserMapper;
import com.ddl.enums.SmsCodeEnum;
import com.ddl.pojo.User;
import com.ddl.redis.RedisKey;
import com.ddl.redis.RedisService;
import com.ddl.service.IUserTokenService;
import com.ddl.service.SmsCodeService;
import com.ddl.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: liyuxiang
 * @create: 2018-11-01
 */
@Service
public class UserServiceImpl implements UserService {

    private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisService redisService;

    @Autowired
    SmsCodeService smsCodeService;

    @Autowired
    IUserTokenService iUserTokenService;

    @Autowired
    IMSingleChatService imSingleChatService;

    // 30天
    private static final Long DEFAULT_TIME_OUT = 60L * 60 * 24 * 30;

    @Override
    public void verifyUser(String userId, String token,Platform platform) throws Exception {
        logger.debug("用户登陆校验:userId={},token={}", userId, token);
        User userInfo = userMapper.selectByPrimaryKey(Integer.parseInt(userId));
        if (userInfo == null) {
            throw new BusinessException(ErrorCode.LOGIN_ERROR_401);
        }

        // 获取用户token
        String userToken = iUserTokenService.getToken(userInfo.getPhone(), platform);
        if (StringUtils.isBlank(userToken)) {
            throw new BusinessException(ErrorCode.LOGIN_ERROR_401);
        }
        if (!userToken.equals(token)) {
            String redisKey = platform.getKey() + ":" + userInfo.getPhone();
            redisService.remove(redisKey);
            throw new BusinessException(ErrorCode.LOGIN_ERROR_405);
        }
    }

    @Override
    public ResultModel register(User user) {
        ResultModel resultModel;

        if (!StringUtils.isEmpty(user.getUserName())) {
            User example = new User();
            example.setUserName(user.getUserName());
            List<User> userList = userMapper.selectBySelective(example);
            if (!CollectionUtils.isEmpty(userList)) {
                return ResultModel.getErrorInstance("用户名已存在，请更换用户名");
            }
        }

        if (!StringUtils.isEmpty(user.getPhone())) {
            User example = new User();
            example.setPhone(user.getPhone());
            List<User> userList = userMapper.selectBySelective(example);
            if (!CollectionUtils.isEmpty(userList)) {
                return ResultModel.getErrorInstance("手机号已存在，请更换用户名");
            }
        }
        smsCodeService.verificationSmsCode(RedisKey.SMS_CODE + user.getPhone() + "_" + SmsCodeEnum.REGISTER.getValue(), user.getSmsCode());
        try {
            user.setCreateTime(new Date());
            userMapper.insertSelective(user);

            List<User> users=userMapper.selectBySelective(user);
            if(users==null||users.size()==0){
                throw new BusinessException(ErrorCode.BUSSINESS_ERROR_201);
            }
            String userId = users.get(0).getId().toString();
            JSONObject regiStr=imSingleChatService.registeredIMID(userId,user.getPassword());
            logger.info("网易云信注册返回结果regiStr={}",regiStr);
            JSONObject updateUserInfo=imSingleChatService.updateUserInfo(userId,user.getUserName(),null,null,user.getSex());
            logger.info("网易云信修改用户信息返回结果updateUserInfo={}",updateUserInfo);
            resultModel = ResultModel.getSuccessInstance();
            resultModel.setMsg("注册成功");
        } catch (Exception e) {
            logger.error("注册失败，user:{}", JSON.toJSON(user), e);
            resultModel = ResultModel.getErrorInstance("注册失败");
        }
        return resultModel;
    }

    @Override
    public ResultModel login(String account, String password) {
        ResultModel resultModel;
        List<User> userList;
        User user = new User();
        user.setUserName(account);
        userList = userMapper.selectBySelective(user);
        if (CollectionUtils.isEmpty(userList)) {
            user = new User();
            user.setPhone(account);
            userList = userMapper.selectBySelective(user);
        }
        if (CollectionUtils.isEmpty(userList)) {
            resultModel = ResultModel.getErrorInstance("该账号没有注册");
        } else {
            user = userList.get(0);
            if (user.getPassword().equalsIgnoreCase(password)) {
                String token = iUserTokenService.createToken(user.getPhone(), "token", Platform.APP);
                user.setToken(token);
                resultModel = ResultModel.getSuccessInstance();
                resultModel.setData(user);
            } else {
                resultModel = ResultModel.getErrorInstance("密码错误");
            }
        }
        return resultModel;
    }

    @Override
    public ResultModel findAccount(String phone, String smsCode, String password) {
        smsCodeService.verificationSmsCode(RedisKey.SMS_CODE + phone + "_" + SmsCodeEnum.FIND_PWD.getValue(), smsCode);
        userMapper.updateByPassword(phone, password);
        return ResultModel.getSuccessInstance();
    }

    @Override
    public ResultModel logOut(String token) {
        redisService.remove(token);
        return ResultModel.getSuccessInstance();
    }

    @Override
    public ResultModel updatePwd(int userId, String oldPwd, String newPwd) {
        ResultModel resultModel;
        User user = userMapper.selectByPrimaryKey(userId);
        if (user.getPassword().equalsIgnoreCase(oldPwd)) {
            user.setPassword(newPwd);
            userMapper.updateByPrimaryKey(user);
            resultModel = ResultModel.getSuccessInstance();
        } else {
            resultModel = ResultModel.getErrorInstance("旧密码不正确");
        }
        return resultModel;
    }

    @Override
    @Transactional
    public ResultModel isFirstLogin(String userId) {
        ResultModel resultModel=ResultModel.getSuccessInstance();
        Map<String,Object> map=new HashMap<>();
        try {
            if(StringUtils.isBlank(userId)){
                map.put("isFirstLogin",1);
                resultModel.setData(map);
                return resultModel;
            }
            User user = userMapper.selectByPrimaryKey(Integer.parseInt(userId));
            map.put("isFirstLogin",user.getIsFirstLogin());
            resultModel.setData(map);
            if(user.getIsFirstLogin()==1){
                User update=new User();
                update.setId(Integer.parseInt(userId));
                update.setIsFirstLogin(0);
                userMapper.updateByPrimaryKeySelective(update);
            }
            return resultModel;
        }catch (Exception e){
            logger.error("是否首次登陆报错{}",e);
            resultModel = ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

}
